package org.naughtybabystudio.android.crazydriver.bluetoothSppManager;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.naughtybabystudio.android.crazydriver.R;

import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class BluetoothDeviceSelectDialog extends Dialog{
	BluetoothAdapter btAdapt = BluetoothAdapter.getDefaultAdapter();
	BluetoothDeviceSelectDialogListener mListener=null;
	ProgressBar mProgressBar=null;
	TextView mStatus=null;
	ListView mDeviceList=null;
	String mFilter=".*";

	Handler mHandler=null;
	
	SimpleAdapter mAdtDevices=null;
	List<HashMap<String,Object>> mLstDevices=new ArrayList<HashMap<String,Object>>();
	
	protected BluetoothDeviceSelectDialog(Context context, BluetoothDeviceSelectDialogListener listener ) {
		super(context,R.style.myDialogStyle);
		mListener=listener;
	}
	public void addDevice(String addr, String name) {
		HashMap<String,Object> map=new HashMap<String,Object>();
		map.put("title",name);
		map.put("addr",addr);
		mLstDevices.add(map);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bluetoothdeviceselect);
		mHandler=new Handler();
		
		mProgressBar=(ProgressBar)findViewById(R.id.pgbBluetoothDeviceSelector);
		mStatus=(TextView)findViewById(R.id.viewStatus);
		mDeviceList = (ListView) this.findViewById(R.id.lvDeviceList);
		
		mAdtDevices=new SimpleAdapter(
				this.getContext(),
				mLstDevices,
				R.layout.bluetoothdeviceselectitem,
				new String[]{"title","addr"},
				new int[]{R.id.tvBluetoothDeviceItemName,R.id.tvBluetoothDeviceItemAddr});
		
		mDeviceList.setAdapter(mAdtDevices);
		mDeviceList.setOnItemClickListener(new ItemClickEvent());
		
		setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface arg0) {
				if( btAdapt!=null && btAdapt.isDiscovering() ) {
					btAdapt.cancelDiscovery();
				}
				unregisterBtBroadcastReceiver();
			}
		});
		
		registerBtBroadcastReceiver();
		
		startSearchDevice();
	}
	
	class ItemClickEvent implements AdapterView.OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			if( btAdapt!=null && btAdapt.isDiscovering() ) {
				btAdapt.cancelDiscovery();
			}
			HashMap<String, Object> device = mLstDevices.get(arg2);
			if( device.containsKey("addr") ) {
				mListener.onDeviceSelected((String)device.get("addr"));
			}
			dismiss();
		}
		
	}
	
    private void registerBtBroadcastReceiver() {
		IntentFilter intent = new IntentFilter();
		intent.addAction(BluetoothDevice.ACTION_FOUND);
		intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
		intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		getContext().registerReceiver(searchDevices, intent);
	}
    
    private void unregisterBtBroadcastReceiver() {
    	getContext().unregisterReceiver(searchDevices);
    }
    
	public BroadcastReceiver searchDevices = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
    		String action=null;
/*    		try {
				action = intent.getAction();
			Bundle b = intent.getExtras();
			Object[] lstName = b.keySet().toArray();
			for (int i = 0; i < lstName.length; i++) {
				String keyName = lstName[i].toString();
				Log.e(keyName, String.valueOf(b.get(keyName)));
			}
			} catch (Exception e) {
				Log.e("liuyi", "Error!!!!");
				return;
			}
*/
    		action = intent.getAction();
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				//find device, add it to the list view
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if( device!=null && device.getName()!=null && device.getName().matches(mFilter) ) {
					
					if( device.getName()!=null && device.getAddress()!=null ) {
						HashMap<String,Object> map=new HashMap<String,Object>();
						map.put("title",device.getName());
						map.put("addr",device.getAddress());
						if(!mLstDevices.contains(map)) {
							mLstDevices.add(map);
							mAdtDevices.notifyDataSetChanged();
						}
					}
				}
			}
			else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				//discovery is finished
				mProgressBar.setVisibility(ProgressBar.GONE);
				if(mLstDevices.size()>0)
					mStatus.setText("Choose one device to connect");
				else
					mStatus.setText("No device found, please try again");
			}
		}
	};
	
	public void setFilter(String str) {
		if( str!=null )
			mFilter=str;
	}

	public void startSearchDevice() {
		
		if( btAdapt==null ) return;
		
		new Thread() {
			@Override
			public void run() {
				
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						mStatus.setText("Opening bluetooth...");
					}
				});
				
				//waiting for bt adapt switch state 
				while( btAdapt.getState()==BluetoothAdapter.STATE_TURNING_OFF
						|| btAdapt.getState()==BluetoothAdapter.STATE_TURNING_ON ) {;}
				
				if( !btAdapt.isEnabled() )
					btAdapt.enable();
				
				//waiting for bt adapt switch state 
				while( btAdapt.getState()==BluetoothAdapter.STATE_TURNING_OFF
						|| btAdapt.getState()==BluetoothAdapter.STATE_TURNING_ON ) {;}
				
				//find device
				if( btAdapt.isEnabled() ) {
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							mStatus.setText("Finding toy vehicle...");
						}
					});
					
					if(btAdapt.isDiscovering())
						btAdapt.cancelDiscovery();
					
					while(btAdapt.isDiscovering()) {;}
					
					if(!btAdapt.isDiscovering())
						btAdapt.startDiscovery();
				
				}
				else {
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							mStatus.setText("Failed to open bluetooth!");
						}
					});
				}
				
			}
			
		}.start();
		
	}
	
}
